export default {
  namespaced:true,
  state:()=>({
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart:JSON.parse(uni.getStorageSync('cart')|| '[]'),
    // cart:[]
  }),
  mutations:{
    addCart(state,goods){
      // 首先判断传过来的商品是否重复的,重复数量就+1,不重复就添加到state中cart数组了里面
      // 1.查找cart中是否有同样的数据
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)//会返回一个布尔值
      console.log('12',findResult);
      if(!findResult){
        state.cart.push(goods)
      }else{
         findResult.goods_count++
      }
      // 通过调用实例中的commit
      this.commit('m_cart/saveCart')
    // console.log(state,goods);
    },
    saveCart(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    updateGoodsState(state,goods){
      // console.log('11',goods);
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        // 对商品状态修改
        findResult.goods_state = goods.goods_state
        // 修改完成后,再次进行持久化
        // console.log(state.cart);
        this.commit('m_cart/saveCart')
      }
    },
    updateGoodsCount(state,goods){
      // console.log('11',goods);
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        // 对商品状态修改
        findResult.goods_count = goods.goods_count
        // 修改完成后,再次进行持久化
        // console.log(state.cart);
        this.commit('m_cart/saveCart')
      }
    },
    removeGoodsById(state,goods_id){
      state.cart = state.cart.filter(x => x.goods_id !== goods_id)
      this.commit('m_cart/saveCart')
    },
    updateAllGoodsState(state,newState){
      state.cart.forEach(x => x.goods_state = newState)
      this.commit('m_cart/saveCart')
    }
  },
  getters:{
    total(state){
      let c = 0;
      state.cart.forEach(goods => {
        c += goods.goods_count
      })
      return c
    },
    checkedCount(state){
      // let c = 0;
      // state.cart.map(item=>{
      //   if(item.goods_state){
      //     c += item.goods_count
      //   }
      // })
      // return c
      return state.cart.filter(x => x.goods_state).reduce((total,item)=> total += item.goods_count,0)
    },
    countPrice(state){
      let c = 0;
      state.cart.map(item=>{
        if(item.goods_state){
          c += item.goods_price * item.goods_count
        }
      })
      return c.toFixed(2)
    },
  },
}